package com.jww.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.jww.pojo.Role;
import com.jww.pojo.User;
import com.jww.service.role.RoleService;
import com.jww.service.role.RoleServiceImpl;
import com.jww.service.user.UserService;
import com.jww.service.user.UserServiceImpl;
import com.jww.util.Constants;
import com.jww.util.PageSupport;
import com.mysql.jdbc.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//实现servlet复用
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method"); // 获取前端的键值对method对应的值
        // 复用servlet
        if (method != null && method.equals("savepwd")) {
            this.updatePwd(req, resp);
        } else if (method != null && method.equals("pwdmodify")) {
            this.pwdModify(req, resp);
        } else if (method != null && method.equals("query")) {
            this.query(req, resp);
        } else if (method != null && method.equals("add")) {
            this.add(req, resp);
        } else if (method != null && method.equals("deluser")) {
            this.delUer(req, resp);
        } else if (method != null && method.equals("getrolelist")) {
            this.getRoleList(req, resp);
        } else if (method != null && method.equals("ucexist")) {
            this.userCodeExist(req, resp);
        } else if (method != null && method.equals("view")) {
            this.getUserById(req, resp, "userview.jsp");
        } else if (method != null && method.equals("modify")) { //对应js里面的 window.location.href=path+"/jsp/user.do?method=modify&uid="+ obj.attr("userid");
            this.getUserById(req, resp, "usermodify.jsp");
        } else if (method != null && method.equals("modifyexe")) { //对应usermodify.jsp里面的<input type="hidden" name="method" value="modifyexe">
            this.modify(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    // 删除用户
    public void delUer(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 在js取
        String id = req.getParameter("uid");
        Integer delId = 0;
        try {
            delId = Integer.parseInt(id);
        } catch (Exception e) {
            delId = 0;
        }
        // System.out.println(delId);
        HashMap<String, String> resultMap = new HashMap<>();
        if (delId <= 0) {
            resultMap.put("delResult", "notexist");
        } else {
            UserService userService = new UserServiceImpl();
            boolean flag = userService.deleteUserById(delId);
            if (flag) {
                resultMap.put("delResult", "true");
            } else {
                resultMap.put("delResult", "false");
            }
        }

        // 返回JSON
        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 添加用户
    public void add(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        System.out.println("add()================");
        String userCode = request.getParameter("userCode");
        String userName = request.getParameter("userName");
        String userPassword = request.getParameter("userPassword");
        String gender = request.getParameter("gender");
        String birthday = request.getParameter("birthday");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");
        String userRole = request.getParameter("userRole");

        // 后端验证：检查所有必填字段是否为空
        if (userCode == null || userCode.trim().isEmpty() ||
                userName == null || userName.trim().isEmpty() ||
                userPassword == null || userPassword.trim().isEmpty() ||
                gender == null || gender.trim().isEmpty() ||
                birthday == null || birthday.trim().isEmpty() ||
                phone == null || phone.trim().isEmpty() ||
                userRole == null || userRole.trim().isEmpty() ||
                "0".equals(userRole)) {

            // 设置错误信息并返回添加页面
            request.setAttribute("error", "所有必填字段都不能为空！");

            // 将用户已填写的数据重新设置到request中，实现数据回显
            User userBack = new User();
            userBack.setUserCode(userCode != null ? userCode : "");
            userBack.setUserName(userName != null ? userName : "");
            userBack.setUserPassword(userPassword != null ? userPassword : "");
            userBack.setGender(gender != null ? Integer.valueOf(gender) : 1);
            userBack.setPhone(phone != null ? phone : "");
            userBack.setAddress(address != null ? address : "");
            userBack.setUserRole(userRole != null && !"0".equals(userRole) ? Integer.valueOf(userRole) : 0);
            // 生日保持原值，让用户看到自己输入的是什么
            userBack.setBirthday(null);

            request.setAttribute("user", userBack);
            request.getRequestDispatcher("useradd.jsp").forward(request, response);
            return;
        }

        User user = new User();
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setAddress(address);
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            // 日期格式错误，设置错误信息并返回
            request.setAttribute("error", "生日日期格式不正确，请选择有效日期！");

            // 将用户已填写的数据重新设置到request中，实现数据回显
            User userBack = new User();
            userBack.setUserCode(userCode);
            userBack.setUserName(userName);
            userBack.setUserPassword(userPassword);
            userBack.setGender(Integer.valueOf(gender));
            userBack.setPhone(phone);
            userBack.setAddress(address);
            userBack.setUserRole(Integer.valueOf(userRole));
            // 生日保持原值，让用户看到自己输入的是什么
            userBack.setBirthday(null);

            request.setAttribute("user", userBack);
            request.getRequestDispatcher("useradd.jsp").forward(request, response);
            return;
        }
        user.setGender(Integer.valueOf(gender));
        user.setPhone(phone);
        user.setUserRole(Integer.valueOf(userRole));
        user.setCreationDate(new Date());
        user.setCreatedBy(((User) request.getSession().getAttribute(Constants.USER_SESSION)).getId());

        UserService userService = new UserServiceImpl();
        if (userService.add(user)) {
            response.sendRedirect(request.getContextPath() + "/jsp/user.do?method=query");
        } else {
            request.setAttribute("error", "添加用户失败，请重试！");

            // 将用户已填写的数据重新设置到request中，实现数据回显
            request.setAttribute("user", user);
            request.getRequestDispatcher("useradd.jsp").forward(request, response);
        }

    }

    // 修改用户信息
    public void modify(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String id = request.getParameter("uid");
        String userName = request.getParameter("userName");
        String gender = request.getParameter("gender");
        String birthday = request.getParameter("birthday");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");
        String userRole = request.getParameter("userRole");

        User user = new User();
        user.setId(Integer.valueOf(id));
        user.setUserName(userName);
        user.setGender(Integer.valueOf(gender));
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(Integer.valueOf(userRole));
        user.setModifyBy(((User) request.getSession().getAttribute(Constants.USER_SESSION)).getId());
        user.setModifyDate(new Date());

        UserService userService = new UserServiceImpl();
        if (userService.modify(user)) {
            response.sendRedirect(request.getContextPath() + "/jsp/user.do?method=query");
        } else {
            request.getRequestDispatcher("usermodify.jsp").forward(request, response);
        }

    }

    // 通过userId查询user
    public void getUserById(HttpServletRequest request, HttpServletResponse response, String url)
            throws ServletException, IOException {

        String id = request.getParameter("uid");
        if (!StringUtils.isNullOrEmpty(id)) {
            // 调用后台方法得到user对象
            UserService userService = new UserServiceImpl();
            User user = userService.getUserById(id);
            request.setAttribute("user", user);
            request.getRequestDispatcher(url).forward(request, response);
        }

    }

    // 根据userCode查询出User 在填写时，判断该用户编码下的用户是否存在，保证用户编码唯一
    private void userCodeExist(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 判断用户账号是否可用
        String userCode = request.getParameter("userCode");

        HashMap<String, String> resultMap = new HashMap<String, String>();
        //userCode 是空字符串或 null，直接认为该账号已存在（或不可用）
        if (StringUtils.isNullOrEmpty(userCode)) {
            // userCode == null || userCode.equals("")
            resultMap.put("userCode", "exist");
        } else {
            UserService userService = new UserServiceImpl();
            User user = userService.selectUserCodeExist(userCode);
            if (null != user) {
                resultMap.put("userCode", "exist");
            } else {
                resultMap.put("userCode", "notexist");
            }
        }

        // 把resultMap转为json字符串以json的形式输出
        // 配置上下文的输出类型
        response.setContentType("application/json");
        // 从response对象中获取往外输出的writer对象
        PrintWriter outPrintWriter = response.getWriter();
        // 把resultMap转为json字符串 输出
        outPrintWriter.write(JSONArray.toJSONString(resultMap));
        outPrintWriter.flush(); // 刷新
        outPrintWriter.close(); // 关闭流
    }

    //查询用户角色
    private void getRoleList(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        List<Role> roleList = null;
        RoleService roleService = new RoleServiceImpl();
        roleList = roleService.getRoleList();
        // 把roleList转换成json对象输出
        response.setContentType("application/json");
        PrintWriter outPrintWriter = response.getWriter();
        outPrintWriter.write(JSONArray.toJSONString(roleList));
        outPrintWriter.flush();
        outPrintWriter.close();
    }

    // 修改密码
    public void updatePwd(HttpServletRequest req, HttpServletResponse resp) {
        // 从Session里面拿ID
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        // 从前端拿到新密码的值
        String newpassword = req.getParameter("newpassword");
        // System.out.println("UserServlet:" + newpassword);
        // 打标记
        boolean flag = false;
        // 判断值是否为空
        if (o != null && newpassword != null) {
            UserService userService = new UserServiceImpl();
            flag = userService.updatePwd(((User) o).getId(), newpassword);
            if (flag) {
                // 给前端请求值
                req.setAttribute("message", "修改密码成功，请退出，使用新密码登录");
                // 密码修改成功，移除当前Session
                req.getSession().removeAttribute(Constants.USER_SESSION);
            } else {
                req.setAttribute("message", "密码修改失败");
            }
        } else {
            req.setAttribute("message", "新密码有问题");
        }

        try {
            req.getRequestDispatcher("pwdmodify.jsp").forward(req, resp);
        } catch (ServletException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 验证旧密码，session中有用户的密码
    public void pwdModify(HttpServletRequest req, HttpServletResponse resp) {
        // 从Session里面拿ID
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");

        // 万能的Map
        Map<String, String> resultMap = new HashMap<>();

        if (o == null) { // session失效了，session过期了
            resultMap.put("result", "sessionerror");
        } else if (oldpassword.length() == 0) // 输入的密码为空
        {
            resultMap.put("result", "error");
        } else {
            String userPassword = ((User) o).getUserPassword();
            if (userPassword.equals(oldpassword)) {
                resultMap.put("result", "true");
            } else {
                resultMap.put("result", "false");
            }
        }

        try {
            // 给浏览器响应一个json的形式
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            /*
             * resultMap = ["result","sessionerror","result","error"] 转成json格式
             * Json格式 = {key : value}
             */
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush(); // 刷新
            writer.close(); // 关闭
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 用户管理
    public void query(HttpServletRequest req, HttpServletResponse resp) {
        // 查询用户列表
        // 从前端获取数据
        String queryUserName = req.getParameter("queryname");
        String temp = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");
        int queryUserRole = 0; // 显示的默认为0

        // 获取用户列表
        UserService userService = new UserServiceImpl();
        List<User> userList = null;

        // 第一次走这个请求，一定是第一页，页面大小固定的；
        int pageSize = 5;
        int currentPageNo = 1;

        // 从前端取出来的数据 进行判断
        if (queryUserName == null) {
            queryUserName = "";
        }
        if (temp != null && !temp.equals("")) {
            queryUserRole = Integer.parseInt(temp); // 给查询赋值！ 0，1，2，3
        }
        if (pageIndex != null) {
            currentPageNo = Integer.parseInt(pageIndex);
        }

        // 获取用户的总数 (分页： 上一页，下一页的情况)
        int totalCount = userService.getUserCount(queryUserName, queryUserRole);
        // 总页数支持
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);

        int totalPageCount = pageSupport.getTotalPageCount();

        // 控制首页和尾页
        // 如果页面小于1了，就显示第一页的东西
        if (currentPageNo < 1) {
            currentPageNo = 1;
        } else if (currentPageNo > totalPageCount) { // 当前页面大于最后一页
            currentPageNo = totalPageCount;
        }

        // 获取用户列表展示
        userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize);
        req.setAttribute("userList", userList);

        RoleService roleService = new RoleServiceImpl();
        List<Role> roleList = roleService.getRoleList();
        req.setAttribute("roleList", roleList);
        req.setAttribute("totalCount", totalCount);
        req.setAttribute("currentPageNo", currentPageNo);
        req.setAttribute("totalPageCount", totalPageCount);
        req.setAttribute("queryUserName", queryUserName);
        req.setAttribute("queryUserRole", queryUserRole);

        // 返回前端
        try {
            req.getRequestDispatcher("userlist.jsp").forward(req, resp);
        } catch (ServletException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
